package com.jair.crawler.tiger;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class demo3 {
	public static SSLSocketFactory getSslSocketFactory(InputStream certificates) {
        SSLContext sslContext = null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

            Certificate ca;
            try {
                ca = certificateFactory.generateCertificate(certificates);

            } finally {
                certificates.close();
            }

            // Create a KeyStore containing our trusted CAs
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            // Create a TrustManager that trusts the CAs in our KeyStore
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            // Create an SSLContext that uses our TrustManager
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return sslContext != null ? sslContext.getSocketFactory() : null;
    }
	

    
    
    public static void main(String[] args) throws IOException{
    	InputStream inputStream = null;
    	try {
    		inputStream =new FileInputStream(new File("D://FiddlerRoot.cer"));
        } catch (IOException e) {
            e.printStackTrace();
        }
		OkHttpClient okHttpClient = new OkHttpClient.Builder()
                 .sslSocketFactory(getSslSocketFactory(inputStream ))
                 .readTimeout(7676, TimeUnit.MILLISECONDS)
                 .connectTimeout(7676, TimeUnit.MILLISECONDS)
                 .build();
		 Request request = new Request.Builder()
		            .url("https://hq1.itiger.com/astock/symbol/meta/600519")
		            .header("User-Agent", "okhttp/3.6.0")
		            .header("Authorization","Bearer xw38v0jXC9b6u6UDrMfvUIBZYXjQlC")
		            .build();
		 
		    Response response = okHttpClient.newCall(request).execute();
		    if (!response.isSuccessful()) {
		        throw new IOException("服务器端错误: " + response);
		    }
		    
		    System.out.println(response.header("Server"));
		    System.out.println(response.message());
		    System.out.println(response.headers("Set-Cookie"));
    }
}
